<template>
    <view>
        <!-- <view class="userBlock" style="padding-top:{{statusBarHeight}}px">
  <view class="userBlock-addr">
    <van-dropdown-menu  active-color="#FFA000">
      <van-dropdown-item value="{{ dropvalue }}" options="{{ dropList }}" bind:change="changeList" />
    </van-dropdown-menu>
  </view>
</view> -->

        <view class="headTitle">
            <view :class="'headTitleTxt ' + (activeIndex == 0 ? 'headTitleTxtActive1' : '')" data-index="0" @tap="changeTab">
                待处理
                <span v-if="orderUnreadCountInfo.pendingCount > 0" class="ordernum">{{ orderUnreadCountInfo.pendingCount }}</span>
            </view>
            <view :class="'headTitleTxt ' + (activeIndex == 1 ? 'headTitleTxtActive2' : '') + ' headTitleTxt2'" data-index="1" @tap="changeTab">
                已接单待配送
                <span v-if="orderUnreadCountInfo.reveiveCount > 0" class="ordernum">{{ orderUnreadCountInfo.reveiveCount }}</span>
            </view>
            <view :class="'headTitleTxt ' + (activeIndex == 2 ? 'headTitleTxtActive3' : '')" data-index="2" @tap="changeTab">
                已配送
                <span v-if="orderUnreadCountInfo.distributeCount > 0" class="ordernum">{{ orderUnreadCountInfo.distributeCount }}</span>
            </view>
            <view :class="'headTitleTxt ' + (activeIndex == 3 ? 'headTitleTxtActive4' : '')" data-index="3" @tap="changeTab">
                已取消
                <span v-if="orderUnreadCountInfo.cancelCount > 0" class="ordernum">{{ orderUnreadCountInfo.cancelCount }}</span>
            </view>
        </view>
        <view class="message-block" v-if="messageList && messageList.length > 0">
            <view class="message-item" @tap="goPage" :data-record="item.id" v-for="(item, index) in messageList" :key="index">
                <view class="message-item-info-title">
                    <image src="/static/assets/img/point.png" class="addrImg" mode="widthFix"></image>
                    <text>{{ item.address }}</text>
                </view>

                <view class="commodityInfo">
                    <!-- <view wx:if="{{activeIndex==1}}" data-id="{{item.id}}" catchtap="sureOrder" class="message-item-info-button">确认配送</view> -->
                    <!-- <view class="message-item-info-content">{{item.commodityName}}</view> -->
                    <view class="commodityInfo-list-item" v-for="(item, index1) in item.commodityList" :key="item.commodityId">
                        <view class="name">{{ item.commodityName }}</view>

                        <view class="count">x{{ item.count }}</view>

                        <view class="price">￥{{ filters.toFix(item.price) }}</view>
                    </view>
                </view>

                <view class="message-item-info-total">
                    订单合计：
                    <text class="dw">¥</text>
                    {{ filters.toFix(item.orderAmount) }}元
                </view>
            </view>
        </view>
        <view v-else>
            <noData />
        </view>
    </view>
</template>
<script module="filters" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
const app = getApp();

const { orderQueryList, orderUpdateStatus, storeQueryPersonalStores, orderUnreadCount } = require('../../utils/api.js');;

export default {
    data() {
        return {
            statusBarHeight: app.globalData.statusBarHeight,
            dropList: [],
            dropvalue: '',
            addressList: [],
            activeIndex: 0,

            //订单状态：0待结单，1已接单待配送，2已配送，3已取消
            searchParams: {
                storeId: '',
                orderStatus: 0,
                //订单状态：0待结单，1已接单待配送，2已配送，3已取消
                personType: 1 //人员类型:0订餐人（居民），1商户管理员
            },

            messageList: [],
            storeId: '',
            personType: 0,
            pageNumber: 1,
            totalPages: 0,

            orderUnreadCountInfo: {
                pendingCount: 0,
                reveiveCount: 0,
                distributeCount: 0,
                cancelCount: 0
            },

            appointList: [],
            roleBusniessType: ''
        };
    },
    onLoad: function (options) {
        if (options.orderStatus) {
            var orderStatus = options.orderStatus;
            this.setData({
                activeIndex: orderStatus || 0
            });
            this.initData();
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.initData();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {},
    onReachBottom: function () {
        if (this.pageNumber + 1 <= this.totalPages) {
            // 若不是最后一页，则将当前页数增加1，获取数据
            this.setData({
                pageNumber: this.pageNumber + 1
            });
            this.getorderQueryList();
        }
    },
    /**
     * 用户点击右上角分享
     */ methods: {
        //获取我的订单列表
        getorderQueryList() {
            let param = {
                phoneNumber: uni.getStorageSync('phoneNumber'),
                //用户手机号：personType为0时必传，为1时不传
                personType: this.personType,
                //人员类型:0订餐人（居民），1商户管理员,
                orderStatus: this.activeIndex || 0,
                //订单状态：0待结单，1已接单待配送，2已配送，3已取消
                storeId: this.storeId,
                //商户ID：personType为1时必传，为0时不传
                page: this.pageNumber,
                limit: 10
            };
            uni.$post(`${orderQueryList}`, param)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        let list = [];
                        list = res.data.content;

                        if (this.pageNumber == 1) {
                            list = res.data.content;
                            this.setData({
                                totalPages: res.data.totalPages
                            });
                        } else {
                            list = this.messageList.concat(res.data.content);
                        }

                        this.setData({
                            messageList: list
                        });
                    } else {
                        this.setData({
                            messageList: []
                        });
                        uni.showToast({
                            title: res.msg || '服务器出小差了',
                            icon: 'none'
                        });
                    }

                    uni.hideNavigationBarLoading(); //完成停止加载

                    uni.stopPullDownRefresh(); //停止下拉刷新
                })
                .catch((err) => {
                    this.setData({
                        messageList: []
                    });
                });
        },

        //更换店铺
        changeList(event) {
            // console.log(event)
            let storeId = event.detail;
            this.searchParams.storeId = storeId; // this.orderUnreadCount();

            this.getData();
        },

        //查询未读订单数量
        orderUnreadCount() {
            var _par = {
                storeId: this.searchParams.storeId
            };
            uni.$post(orderUnreadCount, _par)
                .then((res) => {
                    //请求成功
                    if (res.code == '0') {
                        this.setData({
                            orderUnreadCountInfo: res.data
                        });
                    } else {
                        uni.showToast({
                            title: res.message,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        storeQueryPersonalStores() {
            uni.$post(storeQueryPersonalStores)
                .then((res) => {
                    //请求成功
                    if (res.code == '00000') {
                        let dropList = [];
                        res.data.forEach((item, index) => {
                            dropList.push({
                                text: item.storeName,
                                value: item.storeId
                            });
                        });
                        this.setData({
                            addressList: res.data,
                            dropList,
                            dropvalue: res.data[0].storeId
                        });
                        this.searchParams.storeId = res.data[0].storeId;
                        this.getData();
                        this.orderUnreadCount();
                    } else {
                        uni.showToast({
                            title: res.message,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        goPage(event) {
            let id = event.currentTarget.dataset.record;
            let url;

            if (this.personType == 0) {
                url = `/packageMy/myOrderDetail/myOrderDetail?id=${id}&activeIndex=${this.activeIndex}`;
            } else if (this.personType == 1) {
                url = `/pages/businessOrderMeal2/businessOrderMeal2?id=${id}&activeIndex=${this.activeIndex}`;
            }

            if (this.activeIndex == 2) {
                url = url + '&hideBtn=1';
            }

            uni.navigateTo({
                url
            });
        },

        getData() {
            this.searchParams.orderStatus = this.activeIndex; //  this.data.searchParams.storeId=this.data.activeIndex;

            uni.$post(orderQueryList, this.searchParams).then((res) => {
                if (res.code == '0') {
                    //messageState：1是未读 2是已读
                    this.setData({
                        messageList: res.data.content || []
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        },

        /**
         * 切换Tab
         */
        changeTab(event) {
            let index = event.currentTarget.dataset.index;
            this.setData({
                activeIndex: index || 0,
                pageNumber: 1
            });
            this.getorderQueryList();
        },

        /**
         * 生命周期函数--监听页面加载
         */
        sureOrder(event) {
            let id = event.currentTarget.dataset.id;
            var sureOrderJson = {
                orderStatus: 2,
                id: id
            };
            uni.$post(orderUpdateStatus, sureOrderJson)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        uni.redirectTo({
                            url: '/pages/businessOrderMeal1/businessOrderMeal1?orderStatus=2'
                        });
                    } else {
                        this.setData({
                            appointList: []
                        });
                        uni.showModal({
                            title: '',
                            content: res.msg,
                            showCancel: false,
                            confirmText: '我知道了',
                            confirmColor: '#FFA000',

                            success(res) {
                                uni.redirectTo({
                                    url: '/pages/businessOrderMeal1/businessOrderMeal1?orderStatus=1'
                                });
                            }
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        //获取 员工 我的组织
        getMyorganization(type) {
            let param = {
                staffUnionId: uni.getStorageSync('staffUnionId')
            };

            if (type == 2) {
                this.appQueryDetail();
            }

            uni.$get(api.getMyorganization + `?staffUnionId=${uni.getStorageSync('staffUnionId')}&type=${type}`)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        let dropList = [];
                        let list = res.data;
                        list.forEach((item, index) => {
                            dropList.push({
                                text: item.organizeName,
                                value: item.unionId
                            });
                        });
                        this.setData({
                            addressList: list,
                            dropList,
                            dropvalue: list[0].unionId
                        });

                        if (list.length > 0) {
                            uni.setStorageSync('organizeUnionId', list[0].unionId);
                            uni.setStorageSync('organizeType', list[0].organizeType);
                            uni.setStorageSync('role', list[0].role);
                            this.setData({
                                roleBusniessType: list[0].role.roleBusniessType
                            });
                            this.getMenuByStaff();
                            this.getHomePageDataNew();
                            this.queryStaffWorkListAuth();
                        }
                    } else {
                        uni.showToast({
                            title: res.message,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        initData() {
            this.setData({
                pageNumber: 1
            });
            let roleType = uni.getStorageSync('roleType'); // 3 居民 4 商户

            if (roleType == 3) {
                this.setData({
                    personType: 0
                });
            } else if (roleType == 4) {
                this.setData({
                    personType: 1
                });
            }

            this.getorderQueryList();
        }
    }
};
</script>
<style>
@import './myOrder.css';
</style>
